package com.oe.market.modules.ele.controller;

import com.google.gson.Gson;
import com.oe.market.modules.base.ex.BusinessException;
import com.oe.market.modules.base.model.bean.Account;
import com.oe.market.modules.base.model.bean.RetResponse;
import com.oe.market.modules.base.model.dao.AccountDao;
import com.oe.market.modules.base.model.dto.AccountDto;
import com.oe.market.modules.base.service.AccountService;
import com.oe.market.modules.common.validator.DtoValidator;
import com.oe.market.modules.ele.model.bean.Cookie;
import com.oe.market.modules.ele.model.dao.CookieDao;
import com.oe.market.modules.ele.model.dto.EleRequestDto;
import com.oe.market.modules.ele.service.EleAccountService;
import com.oe.market.modules.ele.service.EleRequestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/v1/ele/account/")
@ResponseBody
public class EleAccountController {
    private static final Logger log = LoggerFactory.getLogger(EleAccountController.class);

    @RequestMapping(value = "/info")
    public String info(HttpServletRequest request) {
        try {
            Account account = AccountService.check(request.getCookies());
            if (account == null) {
                return RetResponse.failedByAccount().toString();
            }

            EleAccountService eleAccountService = new EleAccountService();
            return RetResponse.success("查询成功", eleAccountService.info(account.getAccountId())).toString();
        }
        catch (BusinessException e) {
            return RetResponse.failed(e.getMessage()).toString();
        }
    }

    @RequestMapping(value = "/bind/cookie", method = RequestMethod.POST)
    public String bindCookie(@RequestBody String data, HttpServletRequest request) {
        // 验证账户
        Account account = AccountService.check(request.getCookies());
        if (account == null) {
            return RetResponse.failedByAccount().toString();
        }

        Gson gson = new Gson();
        // 结构化消息类型
        EleRequestDto eleRequestDto = gson.fromJson(data, EleRequestDto.class);
        EleAccountService eleAccountService = new EleAccountService();
        String ret;
        try {
            ret = eleAccountService.bindCookie(eleRequestDto, account.getAccountId());
        } catch (BusinessException e) {
            ret = e.getMessage();
        }

        if (ret != null) {
            return RetResponse.failed(ret).toString();
        }
        return RetResponse.success("绑定成功").toString();
    }
}
